﻿using LD.Tool;
using LdCommunication.Controls;
using PubSub;
using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;

namespace LD.Host
{
    public partial class FrmKazamPressSearch : BaseFrm
    {
        string n_userId = Guid.NewGuid().ToString();
        public FrmKazamPressSearch()
        {
            InitializeComponent();

            if (Appbus.User.CurrentUser.Name != UserType.管理员.ToString())
                this.重新上传KazamToolStripMenuItem.Visible = false;
            else
                this.重新上传KazamToolStripMenuItem.Visible = true;

            this.Shown += FrmKazamPressSearch_Shown;
        }

        private void FrmKazamPressSearch_Shown(object sender, EventArgs e)
        {
            Hub.Default.Subscribe<NotityHandler>(n_userId, (data) => UserChangeNotity(data));
        }
        private void UserChangeNotity(NotityHandler notity)
        {
            if (notity.NtType == NotityType.用户)
            {
                var data = notity.Data as TB_User;
                if (!this.IsDisposed)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (data != null && data.Name == UserType.管理员.ToString())
                            this.重新上传KazamToolStripMenuItem.Visible = true;
                        else
                            this.重新上传KazamToolStripMenuItem.Visible = false;
                    }));
                }
            }
        }
        private void btn_search_Click(object sender, EventArgs e)
        {
            var dataList = DBHelper.Instance.Sql.Queryable<TB_PressData>()
                .Where(p => p.CreateTime >= this.dateTimeS.Value && p.CreateTime <= this.dateTimeE.Value)
                .WhereIF(!string.IsNullOrEmpty(this.txt_barcode.Text), p => p.SN == this.txt_barcode.Text)
                .ToList();
            this.dgv_data.DataSource = dataList;
        }

        private void 重新上传KazamToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dgv_data.SelectedRows.Count == 1)
            {
                var row = this.dgv_data.SelectedRows[0];
                string barcode = row.Cells["条码"].Value.ToString();
                string slot = row.Cells["穴位"].Value.ToString();
                string result = row.Cells["结果"].Value.ToString();
                string data = row.Cells["数据"].Value.ToString();
                if (string.IsNullOrEmpty(barcode)
                    || string.IsNullOrEmpty(slot)
                    || string.IsNullOrEmpty(result)
                    || string.IsNullOrEmpty(data))
                {
                    return;
                }

                string cmd = $"|Result=PASS|Slot={slot.Replace("Slot", "")}|";
                StringBuilder sb = new StringBuilder();
                sb.Insert(0, cmd);

                var success = KazamService.Ins.ClientSend("Kazam", $"CMD=StartOne|Slot={slot.Replace("Slot", "")}|SN={barcode}\r\n");
                if (!success)
                {
                    MessageBox.Show("kazam上传StartOne失败", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                success = KazamService.Ins.ServiceSend_Start(slot, $"CMD=Start|Slot={slot.Replace("Slot", "")}\r\n");

                //监控kazam反馈信息
                if (!MonitorCheckPress(slot))
                {
                    if (!success)
                    {
                        MessageBox.Show("kazam上传Start失败,kazam未相应", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                KazamService.Ins.ServiceSend_Data(slot, sb.ToString());

                var pressData = new TB_PressData()
                {
                    CreateTime = DateTime.Now,
                    Max = 0,
                    Min = 0,
                    Remark = "重复上传",
                    Slot = slot,
                    SN = barcode,
                    TestData = data,
                    Result = "PASS",
                };
                DBHelper.Instance.Sql.Insertable(pressData).ExecuteCommand();
            }
        }
        private bool MonitorCheckPress(string slot)
        {
            bool result = false;
            Stopwatch stopwatch = Stopwatch.StartNew();

            while (stopwatch.ElapsedMilliseconds < 3000)
            {
                var s = KazamService.Ins.getSlotParame(slot);
                if (s != null && s.ClientSendMsg.IndexOf("CheckPress") >= 0)
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
    }
}
